package com.qhx.common.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;


@Slf4j
public class OSSUtil
{
    private static final String endpoint = "oss-cn-zhangjiakou.aliyuncs.com";
    private static final String bucketName = "jzm2004";
    private static final String accessKeyId = "LTAI5tR8KtzLkvRki5b562jh";
    private static final String secretAccessKey = "pu5afSmUyCZMAWy5HtVxmefIvEln5h";

    private static OSS ossClient = null;

    public static String getBucketName()
    {
        return bucketName;
    }

    public static String getEndpoint(){
        return endpoint;
    }



    public static String uploadFile(OSS ossClient, String ossPath, File file) {
        try
        {
            return uploadFile(ossClient,ossPath,new FileInputStream(file));
        } catch (FileNotFoundException e)
        {
            log.error("上传文件io异常:"+e.getMessage());
            return null;
        }
    }

    public static String uploadFile(OSS ossClient, String ossPath, InputStream is){
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            metadata.setContentEncoding("utf-8");
            PutObjectResult putResult = ossClient.putObject(bucketName, ossPath,is, metadata);
            String resultStr = putResult.getETag();
            if(StringUtil.isNull(resultStr)){
                return null;
            }
            return  getUrl(ossClient,bucketName,ossPath);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
            return null;
        }

    }


    public static void deleteObject(OSS ossClient, String url){
        String tempStr = "";
        if(url.contains("?")){ 
            String[] splits = url.split("/?");
            tempStr = splits[0];
        }else{
            tempStr = url;
        }
        String domain =  getOSSDomain();
        String[] split = tempStr.split(domain);
        String key = split[split.length - 1];
        deleteObject(ossClient,bucketName,key);
    }

    public static String getOSSDomain()
    {
        return   getBucketName() + "." + getEndpoint() + "/";
    }


    public static void deleteObject(OSS ossClient, String bucketName, String key) {
        ossClient.deleteObject(bucketName, key);
        log.info("删除" + bucketName + "下的文件" + key + "成功");
    }

    private static String getUrl(OSS ossClient, String bucketName, String key) {
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 99);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        String returnUrl = url.toString();
        return returnUrl;
    }


    public static OSSObject getObject(OSS ossClient,String key){
        OSSObject object = null;
        try {
            object = ossClient.getObject(bucketName, key);
            long fileSize = object.getObjectMetadata().getContentLength();
            String ossPath = object.getKey();
            InputStream is = object.getObjectContent();
            log.info("success to getObject,fileSize:" + fileSize + "\nossPath:" + ossPath + "\ninputStream:" + is);
        } catch (OSSException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return object;
    }





    public static OSS getOssClient()
    {
       return getOssClient(endpoint,accessKeyId,secretAccessKey);
    }

    public static OSS getOssClient(String endpoint, String accessId, String accessKey){
        if (ossClient == null)
        {
            ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
            conf.setMaxConnections(500);
            conf.setSocketTimeout(10000);
            conf.setConnectionTimeout(10000);
            conf.setConnectionRequestTimeout(10000);
            conf.setIdleConnectionTime(10000);
            conf.setMaxErrorRetry(5);
            ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey, conf);
        }
        setCorsOptions(ossClient);
        return ossClient;

    }

    private static void setCorsOptions(OSS ossClient){
        SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);
        ArrayList<SetBucketCORSRequest.CORSRule> putCorsRules = new ArrayList<SetBucketCORSRequest.CORSRule>();

        SetBucketCORSRequest.CORSRule corRule = new SetBucketCORSRequest.CORSRule();

        ArrayList<String> allowedOrigin = new ArrayList<String>();
        allowedOrigin.add( "http://localhost:8111");

        ArrayList<String> allowedMethod = new ArrayList<String>();
        allowedMethod.add("GET");

        ArrayList<String> allowedHeader = new ArrayList<String>();
        allowedHeader.add("x-oss-test");

        ArrayList<String> exposedHeader = new ArrayList<String>();
        exposedHeader.add("x-oss-test1");
        corRule.setAllowedMethods(allowedMethod);
        corRule.setAllowedOrigins(allowedOrigin);
        corRule.setAllowedHeaders(allowedHeader);
        corRule.setExposeHeaders(exposedHeader);
        corRule.setMaxAgeSeconds(10);

        putCorsRules.add(corRule);
        request.setCorsRules(putCorsRules);
        ossClient.setBucketCORS(request);
    }







}
